package com.ruoyi.web.util;

import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.RecursiveTask;

/**
 * ForkJoin 多任务
 * @ProjectName: utils
 * @Package: cn.fulong.web.forkjoin
 * @Author: yu_du_chen
 * @CreateDate: 2019/9/10 16:26
 * @Version: 1.0
 */
@Component
public class ForkJoin{
    /**
     * 单个排序的子任务
     */
    public static class MyTask  extends RecursiveTask<CopyOnWriteArrayList> {

        private CopyOnWriteArrayList<Map<String, Object>> maps;
        private spatial A;
        public MyTask(List<Map<String, Object>> maps,spatial A) {
            this.maps = new CopyOnWriteArrayList(maps);
            this.A = A;
        }

        /* (non-Javadoc)
         * @see java.util.concurrent.RecursiveTask#compute()
         */
        @Override
        protected CopyOnWriteArrayList compute() {
            int sourceLen = maps.size();

            if(sourceLen > 1) {
                int midIndex = sourceLen / 2;
                // 拆分成两个子任务
                MyTask task1 = new MyTask(maps.subList(0, midIndex),A);
                task1.fork();
                MyTask task2 = new MyTask(maps.subList(midIndex, sourceLen),A);
                task2.fork();
                // 结果集合并
                CopyOnWriteArrayList list1 = task1.join();
                CopyOnWriteArrayList list2 = task2.join();
                list1.addAll(list2);
                return list1;
            }else {
                double a = A.xyDistance(Double.parseDouble(maps.get(0).get("position_x").toString()),Double.parseDouble(maps.get(0).get("position_y").toString()));
                //计算出的距离反存入 list
                maps.get(0).put("distance",a);
                return maps;
            }
        }
    }

}
